using FytSoa.Application.Erp.Param;
using FytSoa.Common.Enum;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Masuit.Tools.Reflection;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-调拨服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpTransferService : IApplicationService 
{
    private readonly SugarRepository<ErpTransfer> _thisRepository;
    private readonly SugarRepository<ErpProduct> _productRepository;
    private readonly SugarRepository<ErpTransferProduct> _transferProductRepository;
    private readonly SugarRepository<ErpWarehouseProduct> _warehouseProductRepository;
    private readonly ErpFlowUseService _flowUseService;
    private readonly ErpOperateLogService _operateLogService;
    public ErpTransferService(SugarRepository<ErpTransfer> thisRepository
    ,SugarRepository<ErpProduct> productRepository
    ,SugarRepository<ErpTransferProduct> transferProductRepository
    ,SugarRepository<ErpWarehouseProduct> warehouseProductRepository
    ,ErpFlowUseService flowUseService
    ,ErpOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _productRepository = productRepository;
        _transferProductRepository = transferProductRepository;
        _warehouseProductRepository = warehouseProductRepository;
        _flowUseService = flowUseService;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpTransferDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key))
            .Includes(m=>m.InWarehouse)
            .Includes(m=>m.OutWarehouse)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpTransferDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpTransferByIdDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.InWarehouse)
            .Includes(m=>m.OutWarehouse)
            .FirstAsync(m=>m.Id==id);
        var transferProduct = await _transferProductRepository.GetListAsync(m => m.TransferId == id);
        var productIds = transferProduct.Select(m=>m.ProductId).ToList();
        var productList = await _productRepository.AsQueryable()
            .Where(m => productIds.Contains(m.Id))
            .Includes(m=>m.Type)
            .Includes(m=>m.Unit)
            .Includes(m=>m.Employee)
            .Includes(m=>m.Supplier)
            .ToListAsync();
        var list = productList.Adapt<List<ErpTransferStockProductDto>>();
        foreach (var item in list)
        {
            var productModel = transferProduct.FirstOrDefault(m => m.ProductId == item.Id);
            if (productModel==null) continue;
            item.Count = productModel.Count;
        }

        var result = model.Adapt<ErpTransferDto>();
        result.Flow = await _flowUseService.GetFlowAsync(model.Id);
        return new ErpTransferByIdDto()
        {
            Transfer = result,
            Product = list
        };
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(ErpTransferAddParam model)
    {
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        model.Transfer.Number = "ET".ResNumber(toDay);
        var transferId=await _thisRepository.InsertReturnSnowflakeIdAsync(model.Transfer.Adapt<ErpTransfer>());
        var list = model.Product.Select(item => 
            new ErpTransferProduct() 
                {TransferId = transferId, ProductId = item.Id, Count = item.Count})
            .ToList();
        await _transferProductRepository.InsertRangeAsync(list);
        
        if (model.Transfer.FlowId!=0)
        {
            await _flowUseService.AddAsync(new ErpFlowUseDto()
            {
                FlowId=model.Transfer.FlowId,
                UseId=transferId,
                Type = FlowTypeEnum.TransferStock,
            });
        }
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateId = transferId,
            Type = (int)ErpOperateEnum.Transfer,
            Remark = "创建了调拨信息【"+model.Transfer.Number+"】"
        });
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(ErpTransferAddParam model)
    {
        await _transferProductRepository.DeleteAsync(m => m.TransferId == model.Transfer.Id);
        await _thisRepository.UpdateAsync(model.Transfer.Adapt<ErpTransfer>());
        var list = model.Product.Select(item => 
                new ErpTransferProduct() 
                    {TransferId = model.Transfer.Id, ProductId = item.Id, Count = item.Count})
            .ToList();
        await _transferProductRepository.InsertRangeAsync(list);
        
        if (model.Transfer.Status == ErpAuditEnum.NotReviewed)
        {
            await _flowUseService.ModifyAsync(new ErpFlowUseDto()
            {
                FlowId = model.Transfer.FlowId,
                UseId = model.Transfer.Id,
                Type = FlowTypeEnum.TransferStock,
            });
        }
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateId = model.Transfer.Id,
            Type = (int)ErpOperateEnum.Transfer,
            Remark = "修改了调拨信息【"+model.Transfer.Number+"】"
        });
    }
    
    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyStatusAsync(ErpStatusParam param)
    {
        await _thisRepository.UpdateAsync(m=>new ErpTransfer()
        {
            Status = param.Status
        },m=>m.Id==param.Ids[0]);

        if (param.Status == ErpAuditEnum.Reviewed)
        {
            //处理变更仓库变更业务
            var transfer = await _thisRepository.GetByIdAsync(param.Ids[0]);
            var productIds = await _transferProductRepository.AsQueryable()
                .Where(m => m.TransferId == transfer.Id)
                .Select(m=>m.ProductId)
                .ToListAsync();

            //修改仓库
            await _warehouseProductRepository.UpdateAsync(m => new ErpWarehouseProduct()
            {
                WarehouseId = transfer.InStockId
            },m=>m.WarehouseId==transfer.OutStockId && productIds.Contains(m.ProductId));
        }
        
        if (param.Status==ErpAuditEnum.InReview)
        {
            foreach (var item in param.Ids)
            {
                await _flowUseService.StartAuditAsync(item, FlowTypeEnum.TransferStock);
            }
        }
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateId = param.Ids[0],
            Type = (int)ErpOperateEnum.Transfer,
            Remark = "对调拨进行了审核"+param.Status.GetDescription()+"操作"
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete,UnitOfWork]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _transferProductRepository.DeleteAsync(m => ids.Contains(m.TransferId));
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        await _flowUseService.DeleteAsync(ids);
    }
}
